#!/bin/sh
#by BarryK 2006 for Puppy Linux v2.13+
#passed param is file to be converted.
#converts a .pet file to .tar.gz.
#131122 support xz compressed pets (see dir2pet, installpkg.sh)

exit_error() {
	echo "${PFILE} ERROR: $@"
	exit 1
}

PFILE=$1
[ ! -f "$PFILE" ] && exit_error "no such file"
case $PFILE in
  *.pet) ok=1 ;;
  *) exit_error "only .pet files" ;;
esac

if [ -f /var/local/petget/nd_category ] ; then
  DL_SAVE_FLAG=$(cat /var/local/petget/nd_category)
fi
[ "$DL_SAVE_FLAG" != "true" ] && [ -f /tmp/install_quietly ] && set -x

chmod +w "$PFILE" #make it writable.
FOOTERSIZE="32"
export LC_ALL=C

#determine the compression, extend test to 'XZ'
finfo=$(file -b "$PFILE")
case $finfo in
  gz*|GZ*) EXT=gz ;;
  xz*|XZ*) EXT=xz ;;
  *) exit_error "wrong compression or corrupted/empty file" ;;
esac

MD5SUM="`tail -c $FOOTERSIZE "$PFILE"`"
NEWNAME="`echo -n "$PFILE" | sed -e "s/\\.pet$/\\.tar\\.$EXT/g"`" #131122
#NEWNAME=${PFILE%pet}tar.${EXT}
head -c -$FOOTERSIZE "$PFILE" > $NEWNAME
NEWMD5SUM="`md5sum "$NEWNAME" | cut -f 1 -d ' '`"

sync
[ "$DL_SAVE_FLAG" != "true" ] && rm -f "$PFILE"
if [ ! "$MD5SUM" = "$NEWMD5SUM" ] ; then
	exit_error "MD5 SUMS DON'T MATCH"
fi

exit 0

### END ###
